package org.example.demo.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.demo.common.Result;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * @author wsj
 */
@RestController
@Slf4j
@RequestMapping("/ai")
@RequiredArgsConstructor
public class testController {

    private final ChatClient chatClient;
    @GetMapping("/test")
    public Result test(@RequestParam(defaultValue = "你好啊") String prompt) {
        try {
            String response = chatClient.prompt().user(prompt).call().content();
            log.info("Chat response: {}", response);
            return Result.success(response);
        } catch (Exception e) {
            log.error("Chat error: prompt={}", prompt, e);
            return Result.error("请求失败: " + e.getMessage());
        }
    }

    @GetMapping(value = "/streamTest",  produces = "text/html;charset=utf-8")
    public Flux<String> streamTest(@RequestParam(defaultValue = "你好啊") String prompt) {
        try {
            Flux<String> response = chatClient.prompt().user(prompt).stream().content();
            log.info("Chat response: {}", response);
            return response;
        } catch (Exception e) {
            log.error("Chat error: prompt={}", prompt, e);
            return Flux.error(e);
        }
    }

    @PostMapping("/stream")
    public Result stream(@RequestBody String prompt) {
        String response = chatClient.prompt().user(prompt).call().content();
        log.info("Chat response: {}", response);
        return Result.success(response);
    }

    @PostMapping("/streamFlux")
    public Flux<String> streamFlux(@RequestBody String prompt) {
        return chatClient.prompt().user(prompt).stream().content();
    }

    @GetMapping("/simple")
    public Map<String, String> completion(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
        return Map.of("completion", chatClient.prompt().user(message).call().content());
    }
}
